<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :area-type="areaType" :areas="treeAreas" v-on:handleNodeClick="onHandleNodeClick"/>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-select v-model="listQuery.unit" class="filter-item" clearable placeholder="单元号"
                       style="margin-left: 20px;width: 110px">
              <el-option
                v-for="item in units"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-input v-model="listQuery.floor" class="filter-item" clearable placeholder="楼层"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-input v-model="listQuery.room_number" class="filter-item" clearable placeholder="门牌号"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-input  v-model="listQuery.device_number" class="filter-item" clearable
                      placeholder="终端编号" style="margin-left: 10px;width: 160px"></el-input>
            <el-date-picker
              style="margin-left: 10px;width: 120px"
              class="filter-item"
              v-model="listQuery.bill_date"
              type="month"
              :picker-options="pickerOption"
              placeholder="选择账期">
            </el-date-picker>
            <el-button  class="filter-item" icon="el-icon-search" style="margin-left:40px"
                        type="primary"
                        @click="getBills">
              查询
            </el-button>
            <el-button  class="filter-item" icon="el-icon-download" :loading="btnLoading" style="margin-left:10px"
                        type="primary"
                        @click="handleExport">
              导出
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              ref="price-alloc"
              :loading="listLoading"
              :data="list"
              border
              fit
              highlight-current-row
              stripe
            >
              <el-table-column
                type="index"
                align="center"
                label="#"
                width="50">
              </el-table-column>
              <el-table-column align="left" label="用户">
                <template v-slot="{row}">
                  <span>{{ row.customer? row.customer.customer_name: '未知' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="类别">
                <template v-slot="{row}">
                  <span>{{ formatType(row.customer.customer_type) }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="地址">
                <template v-slot="{row}">
                  <span>{{ row.device?row.device.install_address:'未知' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="表号">
                <template v-slot="{row}">
                  <span>{{ row.device? row.device.terminal_number : '未知' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="户号">
                <template v-slot="{row}">
                  <span>{{ row.customer? row.customer.refer_number : '未知' }}</span>
                </template>
              </el-table-column>
<!--              <el-table-column align="center" label="付费模式">-->
<!--                <template v-slot="{row}">-->
<!--                  <span>{{ row.price_rate | paymentModel}}</span>-->
<!--                </template>-->
<!--              </el-table-column>-->
              <el-table-column align="center" label="本次用水量">
                <template v-slot="{row}">
                  <span>{{ row.volume}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="累计用水量">
                <template v-slot="{row}">
                  <span>{{ row.volume_total}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="余额">
                <template v-slot="{row}">
                  <span>{{ row.balance}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="账单金额">
                <template v-slot="{row}">
                  <span>{{ row.amount}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="账期">
                <template v-slot="{row}">
                  <span>{{ row.bill_date}} </span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="状态">
                <template v-slot="{row}">
                  <span>{{ row.status === 0 ? '未结算' : '已结算'}} </span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="逾期天数">
                <template v-slot="{row}">
                  <span>{{ row.late_fee_option ? row.late_fee_option.days : '未逾期'}} </span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="滞纳金">
                <template v-slot="{row}">
                  <span>{{ row.late_fee_option  ? row.late_fee_option.amount +'元' : '-'}} </span>
                </template>
              </el-table-column>
              <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="200">
                <template v-slot="{row}">
                  <el-button  size="mini" v-if="row.bill && checkPermission('账单结算')"  type="primary"
                              @click="openBillSettlementWindow(row)">
                    账单详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getBills"/>
            <el-drawer
              title="账单结算"
              size="40%"
              :visible.sync="drawer"
              direction="rtl">
              <el-descriptions  v-if="device !== null" style="margin-left: 20px;margin-right: 20px" direction="vertical" :column="2" border >
                <el-descriptions-item label="用户" :span="2">{{device.customer | customerAddress}}</el-descriptions-item>
                <el-descriptions-item label="设备">{{device.terminal_number}}</el-descriptions-item>
                <el-descriptions-item label="账单号">{{device.bill.bill_sn}}</el-descriptions-item>
                <el-descriptions-item label="账期">{{device.bill.bill_date}}</el-descriptions-item>
                <el-descriptions-item label="出账时间">{{device.bill.create_date | dateFormat}}</el-descriptions-item>
                <el-descriptions-item label="用水量">{{device.bill.volume}}</el-descriptions-item>
                <el-descriptions-item label="费用">{{device.bill.amount}}元</el-descriptions-item>
                <el-descriptions-item label="状态">{{device.bill.status === 0 ? '未结算': '已结算'}}</el-descriptions-item>
                <el-descriptions-item label="结算时间">{{device.bill.update_date | dateFormat}}</el-descriptions-item>
              </el-descriptions>
              <el-button v-if="device && device.bill.status === 0" style="margin-left: 20px;margin-top: 20px"  size="mini"   type="primary"
                          @click="handleBillSettlement()">
                结算
              </el-button>
            </el-drawer>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import Pagination from '@/components/Pagination'
import {getAreaTree} from "@/api/area";
import {checkPermission} from "@/utils/permission"
import BalanceRecordList from "@/views/finance/balance_records.vue";
import {fetchWaterBillList,createWaterBill,settleBill} from "@/api/finance";
import moment from "moment";
import {getCustomerTypeText} from "@/utils";
import {exportExcel} from "@/utils/excel";

export default {
  name: 'Bills',
  components: {BalanceRecordList, Pagination,areas},
  data() {
    return {
      dialogFormVisible: false,
      btnLoading: false,
      drawer: false,
      tableKey: 0,
      listLoading: true,
      list: [],
      areaType: 2,
      treeAreas: [],
      recordTargetId:null,
      total: 0,
      listQuery: {
        area_code: '',
        device_number: '',
        class: '',
        unit: '',
        floor: '',
        room_number: '',
        bill_date:null,
        page: 1,
        pageSize: 20,
      },
      pickerOption: {
        disabledDate(time) {
          const currentMonth = new Date().getMonth();
          const currentYear = new Date().getFullYear();
          const lastMonth = new Date(currentYear, currentMonth, 1);
          // 禁用当前月及以后的所有月份
          return time.getTime() > lastMonth.getTime();
        }
      },
      units: ['一单元', '二单元', '三单元', '四单元', '五单元', '六单元', '七单元', '八单元', '九单元', '十单元'],
      device:null
    };
  },
  filters: {
    customerAddress(customer) {
      if(!customer) {
        return '-'
      }
      return  customer.area_name+'/'+customer.unit+'/'+customer.floor+'楼/'+customer.room_number
    },
    paymentModel(rate) {
      if(rate == null) {
        return '-'
      }
      return rate.payment_model === 1 ? '预付费' : '后付费'
    },
    monthFormat(t){
      if(!t) {
        return '-'
      }
      return moment(t).format('YYYY-MM')
    },
    dateFormat(t){
      if(!t) {
        return '-'
      }
      return moment(t).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  created() {
    this.listQuery.bill_date = moment().subtract(1,'months').format('YYYY-MM')
    this.getBills()
    this.getAreaTree()
  },
  methods: {
    checkPermission,
    getAreaTree() {
      getAreaTree({type: 2}).then(response => {
        this.treeAreas = response.data
      })
    },
    onHandleNodeClick: function (data) {
      if (this.listQuery.area_code !== data.code) {
        this.listQuery.area_code = data.code
        this.getBills()
      }
    },
    getBills() {
      if(!this.listQuery.bill_date) {
        this.$message.warning('请选择账期')
        return
      }
      this.listLoading = true
      let query = Object.assign({}, this.listQuery)
      query.bill_date = moment(this.listQuery.bill_date).format('YYYY-MM')
      fetchWaterBillList(query).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    formatType(value){
      return getCustomerTypeText(value)
    },
    openBillSettlementWindow(row) {
      this.drawer = true
      this.device = row
    },
    handleBillSettlement() {
      let row = this.device
      let message = '设备['+row.terminal_number+'],账期['+row.bill.bill_date+'],金额['+row.bill.amount+']是否结算？'
      this.$confirm(message, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        settleBill({bill_id:row.bill.id}).then(resp => {
          if(resp.code === 20000) {
            if(resp.message.length >0 ) {
              this.$message.error(resp.message.join(';'))
            }else {
              this.$message.success('出账操作完成')
            }
            this.getBills()
          }
        })
      }).catch((e) => {
        if (e === 'cancel') {
          row.status = 1
        }else {
          this.$message.error(e)
        }
      })
    },
    handleExport() {
      if(!this.listQuery.bill_date) {
        this.$message.warning('请选择账期')
        return
      }
      this.btnLoading = true
      let query = Object.assign({}, this.listQuery)
      query.bill_date = moment(this.listQuery.bill_date).format('YYYY-MM')
      query.pageSize = 50000
      fetchWaterBillList(query).then(response => {
        const headers = ['姓名','类别','地址','表号','户号','用水量','账单金额','账期','逾期天数','滞纳金']
        const data = response.data.list.map(item => ({
          姓名: item.customer ? item.customer.customer_name : '未知',
          类别: this.formatType(item.customer ? item.customer.customer_type : 0),
          地址: item.device ? item.device.install_address : '未知',
          表号: item.device ? item.device.terminal_number : '未知',
          户号: item.customer ? item.customer.refer_number : '未知',
          用水量: item.volume,
          账单金额: item.amount,
          账期: item.bill_date,
          逾期天数: item.late_fee_option ? item.late_fee_option.days : '0',
          滞纳金: item.late_fee_option  ? item.late_fee_option.amount: '0',
          是否结算: item.status === 0 ? '未结算' : '已结算',
        }))
        exportExcel(data, headers, '水费账单')
        setTimeout(() => {
          this.btnLoading = false
        }, 1.5 * 1000)
      })
    },
    resetQueryParams() {
      this.listQuery = {
        id: 0,
        page: 1,
        pageSize: 20,
        name: ''
      }
    }
  }
}
</script>
